package com.bike.bikeserver.service.impl;

/**
 * @version 1.0
 * @Author ZZX
 * @Date 2023/10/20 22:36
 */
import cn.dev33.satoken.stp.StpInterface;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bike.bikeserver.common.enums.UserKey;
import com.bike.bikeserver.domain.SysRole;
import com.bike.bikeserver.domain.User;
import com.bike.bikeserver.domain.WXUser;
import com.bike.bikeserver.mapper.SysRoleMapper;
import com.bike.bikeserver.mapper.UserMapper;
import com.bike.bikeserver.mapper.WXUserMapper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.bike.bikeserver.constant.Constants.BACK_USER_PREFIX;

/**
 * 自定义权限加载接口实现类
 */
@Component    // 保证此类被 SpringBoot 扫描，完成 Sa-Token 的自定义权限验证扩展
public class StpInterfaceImpl implements StpInterface
{
    @Resource
    SysRoleMapper sysRoleMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    WXUserMapper wxUserMapper;


    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType)
    {
        List<String> list = new ArrayList<String>();
        list.add(getSysRoleByLoginId(loginId).getUserRight());

        return list;
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType)
    {
        List<String> list = new ArrayList<String>();
        list.add(getSysRoleByLoginId(loginId).getUserType());

        return list;
    }

    public SysRole getSysRoleByLoginId(Object loginId)
    {
        // 根据:拆分loginId
        String loginUser = loginId.toString();
        String[] split = loginUser.split(":");
        String userSource = split[0] + ":";
        Integer userId = Integer.parseInt(split[1]);
        String userKey = "";
        if (BACK_USER_PREFIX.equals(userSource))
        {
            User user = userMapper.selectById(userId);
            userKey = user.getAccount();
        } else
        {
            WXUser wxUser = wxUserMapper.selectById(userId);
            userKey = wxUser.getOpenid();
        }
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRole::getUserSource, UserKey.BEHIND.getValue());
        wrapper.eq(SysRole::getUserKey, userKey);
        SysRole sysRole = sysRoleMapper.selectOne(wrapper);
        return sysRole;
    }

}
